package com.xmmxjy.upload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@Controller
@CrossOrigin("*")
@RequestMapping("/test")
public class UploadController {

    @Autowired
    protected HttpServletRequest request;

    @GetMapping("/upload")
    public String upload(Model model) {
        model.addAttribute("ctx",request.getContextPath());
        model.addAttribute("exts","doc|docx|txt");
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Res upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Res.fail();
        }

        String fileName = file.getOriginalFilename();
        String filePath = "D:\\test\\";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return Res.success("上传成功");
        } catch (IOException e) {
        }
        return Res.fail("上传失败");
    }

    
}
